//
//  CycleCurrentLocation.m
//  Septong
//
//  Created by dihuijun on 17/6/8.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "CycleCurrentLocation.h"

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>


@interface CycleCurrentLocation()<CLLocationManagerDelegate>{
    CLLocationManager *_locationManager;
}

@end
@implementation CycleCurrentLocation

///初始化
+ (instancetype)sharedCycleCurrentLocation{

    static CycleCurrentLocation *location = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        location = [[CycleCurrentLocation alloc]init];
    });
    return location;
    
}

/** 获取当前位置 */
- (void)Cycle_GetCurrentLocation{
    
    if([CLLocationManager locationServicesEnabled])
        
    {
        
        _locationManager = [[CLLocationManager alloc] init];
        
        //设置定位的精度
        
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        _locationManager.distanceFilter = 100.0f;
        
        _locationManager.delegate = self;
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0)
            
        {
            
            [_locationManager requestAlwaysAuthorization];
            
            [_locationManager requestWhenInUseAuthorization];
            
        }
        
        //开始实时定位
        
        [_locationManager startUpdatingLocation];
        
    }
    
}

//实现代理方法：
//在上面的代理方法中
/*** 1.2 定位 */
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status

{
    
    NSLog(@"Longitude = %f", manager.location.coordinate.longitude);
    
    NSLog(@"Latitude = %f", manager.location.coordinate.latitude);
    __weak typeof(self) wself = self;
    
    [_locationManager stopUpdatingLocation];
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:manager.location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        for (CLPlacemark * placemark in placemarks) {
            
            NSLog(@"addressDictionary:%@",[placemark addressDictionary]);
            
            NSDictionary *test = [placemark addressDictionary];
            
            //  Country(国家)  State(城市)  SubLocality(区)
            
//            ()
            //国家
            NSString  *Country = [test objectForKey:@"Country"];
            NSLog(@"Country:%@", Country);
            
            //省
            NSString  *State = [test objectForKey:@"State"];
            NSLog(@"省State:%@", State);
            //市
            NSString  *City = [test objectForKey:@"City"];
            NSLog(@"市City:%@", City);
            
            //区
            NSString  *SubLocality = [test objectForKey:@"SubLocality"];
            NSLog(@"区SubLocality:%@", SubLocality);
            
            //街道
            NSString  *Street = [test objectForKey:@"Street"];
            NSLog(@"街道Street:%@",Street );
            
            
            
            NSLog(@"\n城市title: %@  \n 详细地址subTitle: %@", placemark.name,placemark.locality);
            
            
            //具体省市区（不包含中国,街道）
            NSString *detailPlace1 = [NSString stringWithFormat:@"%@%@%@",State,City,SubLocality];
            //具体省市区（不包含中国，包含街道）
            NSString *detailPlace2 = [NSString stringWithFormat:@"%@%@%@%@",State,City,SubLocality,Street];
            //具体省市区（包含中国）
            NSString *detailPlace3 = [NSString stringWithFormat:@"%@%@%@%@%@",Country,State,City,SubLocality,Street];
            
            NSLog(@"具体地点1：%@   --- 具体地点2:%@",detailPlace1,detailPlace2);
            
            ///返回出去
            if (wself.addressBlock) {
                wself.addressBlock(Country,State, City, SubLocality,Street, detailPlace1,detailPlace2,detailPlace3, manager.location.coordinate.longitude, manager.location.coordinate.latitude);
            }
          
        }
        
    }];
    
    
}


#pragma mark - calculate distance  根据2个经纬度计算距离

#define PI 3.1415926
/** 2.根据 2 点经纬度计算距离（千米） */
+(double)cycle_LantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2{
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist/1000.0;
}
/**  3. 系统自带的方法计算距离（千米）*/
+ (double)cycle_startLatitude:(double)startlat startLongtitude:(double)startLon endLatitude:(double)endLat endLongtitude:(double)endLon{
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:startlat  longitude:startLon];
    CLLocation * dist=[[CLLocation alloc] initWithLatitude:endLat longitude:endLon];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
    
    return kilometers;
}




/**
 * 4.弹出弹窗，显示当前设备上安装的定位app(eg:高德地图，百度地图)，选择后跳转到定位app上定位
 * 注意添加白名单：
 在 info.plist 文件里面，添加一个字段：LSApplicationQueriesSchemes里面在加上
 comgooglemaps 谷歌
 iosamap  高德
 baidumap 百度
 */
+ (void)cycle_alertLocationWithLatitude:(CGFloat)latitude longitude:(CGFloat)longitude{
    NSMutableArray *mapArray = [NSMutableArray array];
    NSString *appMapName     = @"苹果自带地图";
    NSString *baiduMapName   = @"百度地图";
    NSString *gaodeMapName   = @"高德地图";
    NSString *googleMapName  = @"谷歌地图";
    [mapArray addObject:appMapName];
    ///百度地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        [mapArray addObject:baiduMapName];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [mapArray addObject:gaodeMapName];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        [mapArray addObject:googleMapName];
    }
    
    UIAlertController *actionAlertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSString *name in mapArray) {
        UIAlertAction *nameAction = [UIAlertAction actionWithTitle:name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([action.title isEqualToString:appMapName]) {
                NSLog(@"%@",appMapName);
                
                CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(latitude, longitude);
                    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
                    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:loc addressDictionary:nil]];
                    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                                   MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
                
            } else if([action.title isEqualToString:baiduMapName]){
                NSLog(@"%@",baiduMapName);//百度地图
                NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            } else if([action.title isEqualToString:gaodeMapName]){
                NSLog(@"%@",gaodeMapName);//高德地图
                NSString *appName = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleDisplayName"];
                NSString *appTJWGaoDeUrlScene = @"appTJWGaoDeUrlScene";
                NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,appTJWGaoDeUrlScene,latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            } else if([action.title isEqualToString:googleMapName]){
                NSLog(@"%@",googleMapName);//谷歌地图
                NSString *appName = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleDisplayName"];
                NSString *appTJWGoogleUrlScene = @"appTJWGoogleUrlScene";
                NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,appTJWGoogleUrlScene,latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
                
            }
        }];
        [actionAlertVC addAction:nameAction];
    }
    //取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [actionAlertVC addAction:cancelAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:actionAlertVC animated:YES completion:nil];
}

/**
 * 客服电话
 */
+ (void)cycle_customerHotLine:(NSString *)ServiceHotLine{
    if (ServiceHotLine.length == 0) {
        [self cycle_showErrorMessage:@"电话号码不能为空"];
        return;
    }
    NSString *callPhone = [[NSString alloc] initWithFormat:@"tel:%@",ServiceHotLine];
    /// 解决iOS10及其以上系统弹出拨号框延迟的问题
    /// 10及其以上系统
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        // Fallback on earlier versions
        /// 10以下系统
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];

    }
}

///显示提示
+ (void)cycle_showErrorMessage:(NSString *)message{
    
    UIAlertView  * alert  = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"我知道了", nil];
    [alert show];
    
}

@end
